<?php namespace Framework\Model;

use Pdo;

class Db
{
	public $table;

	private $pdo;

	private $option=[
		'where'=>'',
		'groupBy'=>'',
		'having'=>'',
		'orderBy'=>'',
		'limit'=>'',
	];

	public function __construct($table)
	{
		$this->table = $table;
		$this->connect();
	}

	private function connect()
	{
		$dsn = 'mysql:host='.C('db_host').';dbname='.C('db_database');
		try{
			$this->pdo = new Pdo($dsn,C('db_user'),C('db_password'));
			$this->pdo->query("set names utf8");
		}catch(PDOException $e) {
			p($e->getMessage());
			exit;
		}

	}

	//只做查询
	public function query($sql,$params=[])
	{
		# select * from stu where id>? and age=? [1,3] 
		
		$sth = $this->pdo->prepare($sql);
		$id=0;
		foreach($params as $p)
		{
			$id++;
			$var = "hd{$id}";
			$$var = $p;
			$sth->bindParam($id, $$var, PDO::PARAM_STR);
		}
		$sth->execute();
		return $sth->fetchAll(PDO::FETCH_ASSOC);
	}

	//执行 (DELETE UPDATE INSERT)
	public function execute($sql,$params =[])
	{
		$sth = $this->pdo->prepare($sql);
		$id=0;
		foreach($params as $p)
		{
			$id++;
			$var = "hd{$id}";
			$$var = $p;
			$sth->bindParam($id, $$var, PDO::PARAM_STR);
		}

		return $sth->execute();

	}
	public function select()
	{
		$sql = 'SELECT * FROM '.$this->table.
		" {$this->option['where']} {$this->option['groupBy']} 
		{$this->option['having']} {$this->option['orderBy']} 
		{$this->option['limit']} ";
		return $this->query($sql);
	}

	public function where($arg)
	{
		$this->option['where']=" WHERE $arg";
		return $this;
	}

	public function limit($arg)
	{
		$this->option['limit']=" LIMIT $arg";
		return $this;
	}
	public function orderBy($arg)
	{
		$this->option['orderBy']=" ORDER BY $arg";
		return $this;
	}
	public function groupBy($arg)
	{
		$this->option['groupBy']=" GROUP BY $arg";
		return $this;
	}
	public function having($arg)
	{
		$this->option['having']=" HAVING $arg";
		return $this;
	}

}







